package com.shouhuobao.take.parcel;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.model.ContactPeopleBean;
import com.shouhuobao.take.weight.indexbar.CharacterParser;
import com.shouhuobao.take.weight.indexbar.SlideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by joker on 2017/7/14.
 */
public class ParcelSelectReceiverActivity extends BaseActivity2 implements SlideBar.OnTouchAssortListener {

    private ListView mListView;// 快递公司列表
    private EditText mSerachET;// 搜索编辑框
    private FrameLayout mFrameLayout;// 正常显示的整体布局
    private ListView mSerachLV;// 搜索时展示使用
    private SlideBar mSlideBar;

    private ArrayList<ContactPeopleBean> alls = null;

    private ParcelSelectReceiverAdapter mAdapter = null;

    @Override
    protected void findViewById() {
        setContentView(R.layout.take_parcel_receiver);
        super.findViewById();
        alls = (ArrayList<ContactPeopleBean>) getIntent().getSerializableExtra("items");
        getAppTitle().setCommonTitle("选择联系人");
        mListView = (ListView) findViewById(R.id.listView);
        mSlideBar = (SlideBar) findViewById(R.id.slidebar);
        mSerachET = (EditText) findViewById(R.id.serachET);
        mSerachLV = (ListView) findViewById(R.id.serachLV);
        mFrameLayout = (FrameLayout) findViewById(R.id.normalFL);
        mSlideBar.setOnTouchAssortListener(this);
        mAdapter = new ParcelSelectReceiverAdapter(alls, getContext());
        mListView.setAdapter(mAdapter);
        mSerachET.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        if (isEmpty(mSerachET.getText().toString())) {
                            mFrameLayout.setVisibility(View.VISIBLE);
                            mSerachLV.setVisibility(View.GONE);
                            mSerachLV.setAdapter(null);
                        } else {
                            mFrameLayout.setVisibility(View.GONE);
                            mSerachLV.setVisibility(View.VISIBLE);
                            mSerachLV.setAdapter(null);
                            serachData(mSerachET.getText().toString());
                        }
                    }
                }
            };

            @Override
            public void afterTextChanged(Editable s) {
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 500);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ContactPeopleBean bean = (ContactPeopleBean) mListView.getAdapter().getItem(position);
                if (bean != null) {
                    Intent intent = new Intent();
                    intent.putExtra("item", bean);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

            }
        });
        //搜索出来的结果、点击以后跳转
        mSerachLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ContactPeopleBean bean = (ContactPeopleBean) mSerachLV.getAdapter().getItem(position);
                if (bean != null) {
                    Intent intent = new Intent();
                    intent.putExtra("item", bean);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            }
        });
        if (alls != null) {
            initData();
        } else {
            showLoadingDialog(null);
            AppHttp.getInstance().getReceiverInfo();
        }
    }

    private void initData() {
        if (alls != null && alls.size() > 0) {
            CharacterParser parser = CharacterParser.getInstance();
            for (int i = 0; i < alls.size(); i++) {
                ContactPeopleBean bean = alls.get(i);
                bean.setItem_type(ContactPeopleBean.TYPE_DATA);
                if (isEmpty(bean.getName())) {
                    bean.setName("#");
                }
                String item_en = parser.getSelling(bean.getName()).toUpperCase().trim();
                if (!item_en.matches("[A-Z]+")) {
                    bean.setItem_en("#" + item_en);
                } else {
                    bean.setItem_en(item_en);
                }
            }
            sortList(alls);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 根据关键字模糊搜索
     *
     * @param content 搜索的内容
     */
    private void serachData(String content) {
        ArrayList<ContactPeopleBean> serachList = new ArrayList<ContactPeopleBean>();
        if (alls != null && alls.size() > 0) {
            for (ContactPeopleBean bean : alls) {
                if (bean.getPhone().startsWith(content)) {
                    serachList.add(bean);
                }
            }
        }
        mSerachLV.setAdapter(new ParcelSelectReceiverAdapter(serachList, getContext()));
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //获取联系人
            case MsgID.parcel_receive_info:
                cancelLoadingDialog();
                ReqResult<ContactPeopleBean> result1 = JSON.parseList(msg.obj, ContactPeopleBean.class);
                if (checkLoginStatus(result1)) {
                    showToast(result1.getMessage());
                    alls = result1.getResultList();
                    initData();
                } else {
                    showToast(result1.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onTouchAssortListener(String s) {
        int select = getSelectIndex(s);
        if (select != -1) {
            mListView.setSelection(select);
        }
    }

    private int getSelectIndex(String s) {
        for (int i = 0; i < alls.size(); i++) {
            String name = alls.get(i).getName();
            if (name.equals(s)) {
                return i;
            }
        }
        return -1;
    }

    private void sortList(List<ContactPeopleBean> list) {
        List<ContactPeopleBean> _List = new ArrayList<ContactPeopleBean>();
        Collections.sort(list, new PinyinComparator());
        ContactPeopleBean dataBean = new ContactPeopleBean(getFirstCharacter(list.get(0).getItem_en()), ContactPeopleBean.TYPE_CHARACTER);
        String currentCharacter = getFirstCharacter(list.get(0).getItem_en());
        _List.add(dataBean);
        _List.add(list.get(0));
        for (int i = 1; i < list.size(); i++) {
            if (getFirstCharacter(list.get(i).getItem_en()).compareTo(currentCharacter) != 0) {
                currentCharacter = getFirstCharacter(list.get(i).getItem_en());
                dataBean = new ContactPeopleBean(currentCharacter, ContactPeopleBean.TYPE_CHARACTER);
                _List.add(dataBean);
            }
            _List.add(list.get(i));
        }
        list.clear();
        for (ContactPeopleBean bean : _List) {
            list.add(bean);
        }
    }

    private String getFirstCharacter(String str) {
        return str.substring(0, 1);
    }

    private class PinyinComparator implements Comparator<ContactPeopleBean> {
        public int compare(ContactPeopleBean o1, ContactPeopleBean o2) {
            if (o1.getItem_en().equals("@")
                    || o2.getItem_en().equals("#")) {
                return -1;
            } else if (o1.getItem_en().equals("#")
                    || o2.getItem_en().equals("@")) {
                return 1;
            } else {
                return o1.getItem_en().compareTo(o2.getItem_en());
            }
        }

    }
}